package cn.xuyun.cc.tcp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import cn.xuyun.cc.tcp.bean.CommandReq;
import cn.xuyun.cc.tcp.service.MongoService;
import cn.xuyun.cc.tcp.vo.Entity;

public class TcpServerHandler extends SimpleChannelUpstreamHandler {

	private static final Logger logger = Logger.getLogger(TcpServerHandler.class);

	public static final ConcurrentHashMap<Integer, String> channel_device = new ConcurrentHashMap<Integer, String>();

	static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

		String[] entity = (String[]) e.getMessage();

		int time = (int) (new Date().getTime() / 1000);

		String deviceid = null;

		if (entity[0].equals("101")) {
			// 设备注册
			logger.info("send to client 11111");

			channel_device.put(e.getChannel().getId(), deviceid);

			e.getChannel().write("$102&0&0#");
			
		} else {
			// response
			deviceid = channel_device.get(e.getChannel().getId());
			// MongoService.saveResponse(deviceid, entity);

			CommandReq cmdreq = MongoService.getCmdreq(deviceid);
			logger.info("deviceId:" + deviceid);
			logger.info("cmdreq:" + cmdreq);
			if (cmdreq != null) {
				// 有命令要执行
				Entity cmd = new Entity(time, 1, 0, 0, cmdreq.getCmdcode(), cmdreq.getParam().getBytes(), 0);
				e.getChannel().write(cmd);
			}
		}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		e.getCause().printStackTrace();
		e.getChannel().close();
	}
}
